<template>
  <view class="container">
    <!-- 表单组件 -->
    <view class="form-wrapper">
      <u-form :model="form" ref="uForm" label-width="140rpx">
        <u-form-item label="商品名称" prop="goods_name">
          <u-input v-model="form.goods_name" placeholder="请输入商品名称" />
        </u-form-item>
        <u-form-item label="商品编码" prop="goods_no">
          <u-input class="form-no" v-model="form.goods_no" placeholder="请输入商品编码" />
		  <u-icon name="scan" size="36" @click="handelScanCode()"></u-icon>
        </u-form-item>
		<u-form-item label="商品分类" prop="categoryIds">
          <select-category v-model="categoryIds"/>
		</u-form-item>
        <u-form-item label="商品图片" prop="imagesIds">
          <!-- <u-input v-model="form.imagesIds" placeholder="请输入商品图片" /> -->
        </u-form-item>
        <u-form-item>
		  <!-- 图片列表 -->
		  <view class="image-list">
		    <view class="image-preview" v-for="(image, imageIndex) in imageList" :key="imageIndex">
		      <text class="image-delete iconfont icon-shanchu" @click="deleteImage(imageIndex)"></text>
		      <image class="image" mode="aspectFill" :src="image.path"></image>
		    </view>
		    <view v-if="!imageList || imageList.length < maxImageLength" class="image-picker"
		      @click="chooseImage()">
		      <text class="choose-icon iconfont icon-camera"></text>
		      <text class="choose-text">上传图片</text>
		    </view>
		  </view>
		</u-form-item>
        <u-form-item label="商品价格" prop="goods_price">
          <u-input v-model="form.goods_price" placeholder="请输入商品价格" />
        </u-form-item>
        <u-form-item label="所需积分" prop="goods_price">
          <u-input v-model="form.points" placeholder="请输入兑换所需积分" />
        </u-form-item>
        <u-form-item label="划线价" prop="line_price">
          <u-input v-model="form.line_price" placeholder="请输入划线价" />
        </u-form-item>
        <u-form-item label="商品库存" prop="stock_num">
          <u-input v-model="form.stock_num" placeholder="请输入商品库存" />
        </u-form-item>
		<u-form-item label="赠送积分" prop="give_points">
		  <u-input v-model="form.give_points" placeholder="请输入购买后赠送积分数量" />
		</u-form-item>
		
        <u-form-item label="商品状态" prop="status">
          <u-radio-group v-model="form.status">
			<u-radio name="10">上架</u-radio>
			<u-radio name="20">下架</u-radio>
		  </u-radio-group>
        </u-form-item>
        <u-form-item label="商品详情" prop="content">
          <u-input v-model="form.content" placeholder="请输入商品详情" />
        </u-form-item>
      </u-form>
    </view>
	  <view style="height: 200rpx;"></view>
	  <!-- 底部操作按钮 -->
	  <view class="footer-fixed">
	    <view class="btn-wrapper">
	      <view class="btn-item btn-item-main" :class="{ disabled }" @click="handleSubmit()">保存</view>
	    </view>
	  </view>
  </view>
</template>

<script>
  import SelectCategory from '@/components/select-category/select-category'
  import Verify from '@/utils-shop/verify'
  import * as GoodsApi from '@/apishop/goods'
  import * as UploadApi from '@/apishop/upload'

  const maxImageLength = 6
  
  // 表单字段元素
  const form = {
	goods_name: '',
	categoryIds: [],
	imagesIds: [],
	goods_no: '',
	spec_type: 10,
	stock_num: 0,
	goods_price: 0,
	line_price: 0,
	points: 0,
	give_points: 0,
	content: '',
	status: 10,
	is_enable_grade: 0,
	serviceIds: [],
  }

  // 表单验证规则
  const rules = {
    goods_name: [{
      required: true,
      message: '请输入商品名称',
      trigger: ['blur', 'change'],
    }],
    goods_price: [{
      required: true,
      message: '请输入商品价格',
      trigger: ['blur', 'change']
    }],
    line_price: [{
      required: true,
      message: '请输入划线价',
      trigger: ['blur', 'change']
    }],
    stock_num: [{
      required: true,
      message: '请输入商品库存',
      trigger: ['blur', 'change']
    }],
  }

  export default {
    components: {
      SelectCategory
    },
    data() {
      return {
		categoryIds: [],
	    imageList: [],
        form,
        rules,
        // 最大图片数量
        maxImageLength,
        // 按钮禁用
        disabled: false
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},

    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.uForm.setRules(this.rules)
    },

    methods: {
      // 选择图片
      chooseImage() {
        const app = this
        const oldImageList = app.imageList
		console.log(oldImageList)
        // 选择图片
        uni.chooseImage({
          count: maxImageLength - oldImageList.length,
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success({ tempFiles }) {
            // tempFiles = [{path:'xxx', size:100}]
            app.imageList = oldImageList.concat(tempFiles)
		    console.log(app.imageList)
          }
        });
      },

      // 删除图片
      deleteImage(index) {
        this.imageList.splice(index, 1)
		console.log(this.imageList)
      },
	  
      // 表单提交
      handleSubmit() {
        const app = this
        if (app.disabled) {
          return false
        }
		
        app.$refs.uForm.validate(valid => {
			
          if (valid) {
            app.disabled = true
			app.form.categoryIds = [app.categoryIds[0].value]
			console.log(app.form.categoryIds)
			// 判断是否需要上传图片
			const imagesLength = app.getImagesLength()
			console.log(imagesLength)
			if (imagesLength > 0) {
				console.log('upload_pre')
			  app.uploadFile()
			    .then(() => {
			      console.log('then')
			      app.onSubmit()
			    })
			    .catch(err => {
			      console.log('catch')
			      app.disabled = false
			      if (err.statusCode !== 0) {
			        app.$toast(err.errMsg)
			      }
			      console.log('err', err)
			    })
			} else {
			  app.disabled = false
		      app.$toast('请先上传图片')
			}
          }
        })
      },

      onSubmit() {
		const app = this
	    //提交数据
	    GoodsApi.add(app.form)
		  .then(result => {
			app.$toast(result.message)
			setTimeout(() => {
			  app.disabled = false
			  uni.navigateBack()
			}, 1500)
		  })
		  .finally(() => app.disabled = false)
	  },
	  
	  handelScanCode() {
		const app = this
		uni.scanCode({
			scanType: ['barCode'],  
			success: function (res) {  
				console.log('条码类型：' + res.scanType)
				console.log('条码内容：' + res.result)
				
				form.goods_no = res.result
				// GoodsApi.searchNo(res.result)
				//   .then(result => {
				// 	  console.log(result)
				// 	  const detail = result.data.goodsInfo
				// 	  app.createFormData(detail)
				  // })
			}  
		})
  	  },
	  
	  // 生成默认的表单数据
	  createFormData(detail) {
	    const { form } = this
	    form.goods_name = detail.goods_name
	    form.goods_no = detail.goods_no
		  form.stock_num = detail.stock_total
	    form.goods_price = detail.goods_price_min
		  form.points = detail.points
		  form.give_points = detail.give_points
	    form.line_price = detail.line_price_min
	    form.status = detail.status
	    form.content = detail.content
	    form.imagesIds = detail.imageIds
	    this.imageList = detail.image_list
		  form.categoryIds = detail.categoryIds
		  this.categoryIds = this.createCategory(detail)
	  },
	  
	  createCategory(detail) {
	    return [{
	      label: detail.category_name,
	      value: detail.categoryIds[0]
	    }]
	  },
	  
      // 统计图片数量
      getImagesLength() {
        let imagesLength = this.imageList.length
        return imagesLength
      },
	  
      // 上传图片
      uploadFile() {
        const app = this
        const { form } = app
        // 整理上传文件路径
        const files = []
        
        if (app.imageList.length) {
          // const images = app.imageList.map(image => image)
          // files.push({ images })
			  const images = app.imageList.map((item,index,arr)=>{
				  if(typeof(item.size) == 'undefined'){
					return null
				}
				let data = {}
				data.path = item.path
				data.size = item.size
				return data
			  })
			  for(var i = 0; i < images.length; i++) {
				  if(!images[i]) {
					  images.splice(i,1);
					  i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位
				  }
			  }
			  if(images.length){
				  files.push({ images })
			  }
        }
        // 批量上传
        return new Promise((resolve, reject) => {
          Promise.all(files.map((file, index) => {
              return new Promise((resolve, reject) => {
                UploadApi.image(file.images)
                  .then(fileIds => {
					console.log(app.form.imagesIds)
                    app.form.imagesIds = app.form.imagesIds.concat(fileIds)
					console.log(app.form.imagesIds)
                    resolve(fileIds)
                  })
                  .catch(reject)
              })
            }))
            .then(resolve, reject)
        })
      }
    }
  }
</script>

<style>
  page {
    background: #f7f8fa;
  }
</style>
<style lang="scss" scoped>
  .page-title {
    width: 94%;
    margin: 0 auto;
    padding-top: 40rpx;
    font-size: 28rpx;
    color: rgba(69, 90, 100, 0.6);
  }

  .form-wrapper {
    margin: 20rpx auto 20rpx auto;
    padding: 0 40rpx;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    border-radius: 16rpx;
    background: #fff;
  }

  /* 底部操作栏 */

  
  // 底部操作栏
  .footer-fixed {
    position: fixed;
    bottom: var(--window-bottom);
    left: 0;
    right: 0;
    height: 96rpx;
    z-index: 11;
    box-shadow: 0 -4rpx 40rpx 0 rgba(144, 52, 52, 0.1);
    background: #fff;
  
    .btn-wrapper {
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
    }
  
    .btn-item {
      flex: 1;
      font-size: 28rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      color: #fff;
      border-radius: 50rpx;
    }
  
    .btn-item-main {
      background: linear-gradient(to right, #f9211c, #ff6335);
    }
  
  }
  
  
  .image-list {
    padding: 0 20rpx;
    margin-top: 20rpx;
    margin-bottom: -20rpx;
  
    &:after {
      clear: both;
      content: " ";
      display: table;
    }
  
    .image {
      display: block;
      width: 100%;
      height: 100%;
    }
  
    .image-picker,
    .image-preview {
      width: 170rpx;
      height: 170rpx;
      margin-right: 30rpx;
      margin-bottom: 30rpx;
      float: left;
  
      &:nth-child(3n+0) {
        margin-right: 0;
      }
    }
  
    .image-picker {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1rpx dashed #ccc;
      color: #ccc;
  
      .choose-icon {
        font-size: 48rpx;
        margin-bottom: 6rpx;
      }
  
      .choose-text {
        font-size: 24rpx;
      }
    }
  
    .image-preview {
      position: relative;
  
      .image-delete {
        position: absolute;
        top: -15rpx;
        right: -15rpx;
        height: 42rpx;
        width: 42rpx;
        line-height: 42rpx;
        background: rgba(0, 0, 0, 0.64);
        border-radius: 50%;
        color: #fff;
        font-weight: bolder;
        font-size: 22rpx;
        z-index: 10;
        text-align: center;
      }
    }
  }
  
  .form-no{
	  display: inline-block;
	  width: 80%;
	  vertical-align: top;
  }
  .form-no-scan{
	  display: inline-block;
  }
</style>
